package com.ultrapower.util.rowkey;

import com.sematext.hbase.wd.AbstractRowKeyDistributor;
import com.sematext.hbase.wd.RowKeyDistributorByHashPrefix;
import com.ultrapower.util.BytesUtils;
import com.ultrapower.util.HBaseTables;
import com.ultrapower.util.TransactionId;

public class TraceRowKeyEncoderV2 {
	public static final int AGENT_NAME_MAX_LEN = HBaseTables.AGENT_NAME_MAX_LEN;
	public static final int DISTRIBUTE_HASH_SIZE = 1;

	private final AbstractRowKeyDistributor rowKeyDistributor;

	public TraceRowKeyEncoderV2(AbstractRowKeyDistributor rowKeyDistributor) {
		if (rowKeyDistributor == null) {
			rowKeyDistributor = new RowKeyDistributorByHashPrefix(new RangeOneByteSimpleHash(32, 40, 256));
		}

		this.rowKeyDistributor = rowKeyDistributor;
	}

	public byte[] encodeRowKey(TransactionId transactionId) {
		if (transactionId == null) {
			throw new NullPointerException("basicSpan must not be null");
		}

		byte[] rowKey = BytesUtils.stringLongLongToBytes(transactionId.getAgentId(), AGENT_NAME_MAX_LEN,
				transactionId.getAgentStartTime(), transactionId.getTransactionSequence());
		return wrapDistributedRowKey(rowKey);
	}

	private byte[] wrapDistributedRowKey(byte[] rowKey) {
		return rowKeyDistributor.getDistributedKey(rowKey);
	}
}
